<?php

namespace common\domain\components;

use common\models\BkAdmin;
use Yii;
use yii\db\ActiveRecord;

class AccessToken
{
    /**
     * 创建管理员登陆Token
     * @param ActiveRecord|BkAdmin $user
     * @param int $expire
     * @param int $cache_expire
     * @return string
     * @throws \yii\base\Exception
     */
    public static function createSession(ActiveRecord $user, $expire = 1200, $cache_expire = 0): string
    {
        do {
            $ssid = Yii::$app->getSecurity()->generateRandomString(64);
            $db_data = BkAdmin::findOne(['token' => $ssid]);
        } while ($db_data);

        if ($expire) {
            $user->token = $ssid;
            $user->token_expire_at = time() + $expire;
            $user->save();
        }

        Yii::$app->cache->set(static::getCacheKey($ssid), $user, $cache_expire ?: $expire / 2);

        return $ssid;
    }

    /**
     * 清除session.
     */
    public static function clearSession(string $access_token): void
    {
        Yii::$app->cache->delete(static::getCacheKey($access_token));
        BkAdmin::updateAll(['token' => null, 'token_expire_at' => 0], ['token' => $access_token]);
    }

    /**
     * 获取请求中的AccessToken.
     */
    public static function getRequestAccessToken(): ?string
    {
        $request = Yii::$app->request;
        $access_token = $request->getBodyParam('access_token');
        if (!$access_token) {
            $access_token = $request->get('access_token');
        }
        if (!$access_token) {
            $access_token = $request->getHeaders()->get('Access-Token');
        }

        return $access_token;
    }

    /**
     * 获取缓存key.
     * @param $token
     * @return string
     */
    public static function getCacheKey($token): string
    {
        return 'bk:ssid:' . $token;
    }
}
